package com.wannengbang.cloudleader.homepage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AddressListBean;
import com.wannengbang.cloudleader.bean.CreateOrderBean;
import com.wannengbang.cloudleader.bean.ProductListBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.dialog.InputNumDialog;
import com.wannengbang.cloudleader.event.AddressEvent;
import com.wannengbang.cloudleader.event.ChooseAddressEvent;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.mine.AddAddressActivity;
import com.wannengbang.cloudleader.mine.AddressListActivity;
import com.wannengbang.cloudleader.mine.MyOrderListActivity;
import com.wannengbang.cloudleader.mine.model.IMineModel;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.utils.FastClickUtils;
import com.wannengbang.cloudleader.utils.GlideUtils;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.ViewLoading;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConfirmOrderActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.iv_goods_thumb)
    ImageView ivGoodsThumb;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @BindView(R.id.tv_goods_num)
    TextView tvGoodsNum;
    @BindView(R.id.tv_sort)
    TextView tvSort;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.edit_remark)
    EditText editRemark;
    @BindView(R.id.tv_total_number)
    TextView tvTotalNumber;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_total_number2)
    TextView tvTotalNumber2;
    @BindView(R.id.tv_total_price2)
    TextView tvTotalPrice2;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.iv_check1)
    ImageView ivCheck1;
    @BindView(R.id.ll_deliver_mode)
    LinearLayout llDeliverMode;
    @BindView(R.id.iv_check2)
    ImageView ivCheck2;
    @BindView(R.id.ll_deliver_mode2)
    LinearLayout llDeliverMode2;
    @BindView(R.id.iv_check3)
    ImageView ivCheck3;
    @BindView(R.id.ll_deliver_mode3)
    LinearLayout llDeliverMode3;
    @BindView(R.id.tv_withdrawal_money)
    TextView tvWithdrawalMoney;
    private ProductListBean.DataBean.ItemListBean itemListBean;
    private IMineModel mineModel;
    private String totalPrice;
    private AddressListBean.DataBean.ItemListBean addressBean;
    private IHomePageModel homePageModel;
    private int delivery_type = 1;
    private int is_earnings = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        ButterKnife.bind(this);
        initView();
        registerEventBus();
        requestAddressIndex();
        requestUserInfo();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        mineModel = new MineModelImpl();
        itemListBean = (ProductListBean.DataBean.ItemListBean) getIntent().getSerializableExtra("ItemListBean");

        if (itemListBean != null) {

            GlideUtils.loadImage(mActivity, ivGoodsThumb, itemListBean.getThumb());
            tvGoodsName.setText(itemListBean.getName());
            String price = NumberFormatUtils.formatDouble(Double.parseDouble(itemListBean.getPrice()) / 100);
            tvGoodsPrice.setText("￥" + price);

            //小pos type=1 5台起步 大pos type=2 3台起步
            if (itemListBean.getNumber() == 1) {
                if (itemListBean.getType() == 2) {
                    setTotalPrice(3);
                } else {
                    setTotalPrice(5);
                }
                tvSort.setVisibility(View.VISIBLE);
                tvAdd.setVisibility(View.VISIBLE);
                tvNumber.setEnabled(true);
            } else {
                setTotalPrice(itemListBean.getNumber());
                tvSort.setVisibility(View.GONE);
                tvAdd.setVisibility(View.GONE);
                tvNumber.setEnabled(false);
            }
        }
    }

    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                String withdrawal_money = NumberFormatUtils.formatTwoDecimal((Double.parseDouble(bean.getData().getCan_withdrawal_money())
                        + Double.parseDouble(bean.getData().getFx_can_withdrawal_money())) / 100);
                tvWithdrawalMoney.setText("账户余额(￥" + withdrawal_money + ")支付，总部发货");
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void addressEvent(ChooseAddressEvent event) {
        addressBean = event.getItemListBean();
        tvName.setText(addressBean.getName());
        tvMobile.setText(addressBean.getMobile());
        tvAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress());
        tvAddress.setVisibility(View.VISIBLE);
    }

    @Subscribe
    public void addressEvent(AddressEvent event) {
        requestAddressIndex();
    }

    public void setTotalPrice(int goodsNum) {
        tvGoodsNum.setText("x" + goodsNum);
        tvNumber.setText(goodsNum + "");
        tvTotalNumber.setText("共" + goodsNum + "件");
        tvTotalNumber2.setText("共" + goodsNum + "件，");
        totalPrice = NumberFormatUtils.formatDouble(goodsNum * Double.parseDouble(itemListBean.getPrice()) / 100);
        tvTotalPrice.setText(totalPrice);
        tvTotalPrice2.setText(totalPrice);
        itemListBean.setCount(goodsNum);
    }

    private void requestAddressIndex() {
        mineModel.requestAddressIndex(1, new DataCallBack<AddressListBean>() {
            @Override
            public void onSuccessful(AddressListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    addressBean = bean.getData().getItemList().get(0);
                    tvName.setText(addressBean.getName());
                    tvMobile.setText(addressBean.getMobile());
                    tvAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress());
                    tvAddress.setVisibility(View.VISIBLE);
                } else {
                    tvName.setText("暂无收货地址请添加");
                    tvMobile.setText("");
                    tvAddress.setText("");
                    tvAddress.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @OnClick({R.id.ll_select_address, R.id.tv_sort, R.id.tv_add, R.id.tv_commit, R.id.tv_number, R.id.ll_deliver_mode, R.id.ll_deliver_mode2, R.id.ll_deliver_mode3})
    public void onViewClicked(View view) {
        int num = 0;
        if (itemListBean == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_select_address:
                if (addressBean == null) {
                    showActivity(AddAddressActivity.class);
                } else {
                    Intent intent = new Intent(mActivity, AddressListActivity.class);
                    intent.putExtra("chooseType", "select_address");
                    startActivity(intent);
                }
                break;
            case R.id.tv_sort:
                num = Integer.parseInt(tvNumber.getText().toString());

                if (itemListBean.getType() == 2) {
                    if (num > 3) {
                        num--;
                    } else {
                        ToastUtil.showShort("购买数量最小为3");
                    }
                } else {
                    if (num > 5) {
                        num--;
                    } else {
                        ToastUtil.showShort("购买数量最小为5");
                    }
                }
                setTotalPrice(num);
                break;
            case R.id.tv_add:
                num = Integer.parseInt(tvNumber.getText().toString());
                num++;
                setTotalPrice(num);
                break;
            case R.id.tv_commit:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (addressBean == null) {
                    ToastUtil.showShort("请添加收货地址");
                    return;
                }
                requestStoreOrderAdd();
                break;
            case R.id.tv_number:
                InputNumDialog dialog = InputNumDialog.newInstance(itemListBean.getType(), tvNumber.getText().toString());
                dialog.show(getSupportFragmentManager(), "dialog");
                dialog.setOnCallBackListener(num1 -> {
                    setTotalPrice(num1);
                });
                break;
            case R.id.ll_deliver_mode:
                delivery_type = 1;
                is_earnings = 0;
                ivCheck1.setImageResource(R.mipmap.ic_order_xuanze);
                ivCheck2.setImageResource(R.mipmap.ic_order_kongyuan);
                ivCheck3.setImageResource(R.mipmap.ic_order_kongyuan);
                break;
            case R.id.ll_deliver_mode2:
                delivery_type = 2;
                is_earnings = 0;
                ivCheck1.setImageResource(R.mipmap.ic_order_kongyuan);
                ivCheck2.setImageResource(R.mipmap.ic_order_xuanze);
                ivCheck3.setImageResource(R.mipmap.ic_order_kongyuan);
                break;
            case R.id.ll_deliver_mode3:
                delivery_type = 1;
                is_earnings = 1;
                ivCheck1.setImageResource(R.mipmap.ic_order_kongyuan);
                ivCheck2.setImageResource(R.mipmap.ic_order_kongyuan);
                ivCheck3.setImageResource(R.mipmap.ic_order_xuanze);
                break;
        }
    }

    /**
     * 创建订单
     */
    public void requestStoreOrderAdd() {
        ViewLoading.showProgress(mActivity, "提交中......");
        itemListBean.setGoods_remark(editRemark.getText().toString());
        itemListBean.setShop_goods_id(itemListBean.getId());
        List<ProductListBean.DataBean.ItemListBean> goodsList = new ArrayList<>();
        goodsList.add(itemListBean);
        homePageModel.requestStoreOrderAdd(addressBean.getId() + "", String.valueOf(delivery_type), String.valueOf(is_earnings), "", goodsList, new DataCallBack<CreateOrderBean>() {
            @Override
            public void onSuccessful(CreateOrderBean bean) {
                ToastUtil.showShort("下单成功");
                //线上付款，总部发货
                if (delivery_type == 1 && is_earnings == 0) {
                    String order_no = bean.getData().getId();
                    Intent intent = new Intent(mActivity, PayOrderActivity.class);
                    intent.putExtra("order_no", order_no);
                    intent.putExtra("totalPrice", totalPrice);
                    intent.putExtra("payPage", "ConfirmOrderActivity");
                    startActivity(intent);
                } else {
                    showActivity(MyOrderListActivity.class);
                }
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
